// 上传模块 - 负责所有内容上传功能
let pastedImageFile = null;

// 页面切换
function showUploadPage() {
    if (!currentUser) {
        alert('请先登录后再上传内容');
        document.getElementById('loginButton').click();
        return;
    }
    
    document.getElementById('searchPage').classList.add('d-none');
    document.getElementById('uploadPage').classList.remove('d-none');
    document.body.style.background = '#f8fafc';
    // 隐藏单独的图片上传表单，统一改为"粘贴截图"或使用"文件上传"
    const imgFormEl = document.getElementById('imageForm');
    if (imgFormEl) imgFormEl.classList.add('d-none');
}

// 处理文本提交
function handleTextSubmit(e) {
    e.preventDefault();
    
    const textContent = document.getElementById('textContent').value.trim();
    if (!textContent) {
        alert('请输入文本内容');
        return;
    }
    
    // 防止重复提交
    const submitBtn = e.target.querySelector('button[type="submit"]');
    if (submitBtn && submitBtn.disabled) {
        return;
    }
    
    // 禁用提交按钮
    if (submitBtn) {
        submitBtn.disabled = true;
    }
    
    showUploadLoading();
    
    const formData = new FormData();
    formData.append('type', 'text');
    formData.append('content', textContent);
    
    fetch('/api/content', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        displayUploadResult(data);
        document.getElementById('textContent').value = '';
        // 重新启用提交按钮
        if (submitBtn) {
            submitBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        displayUploadError(error);
        // 出错时重新启用按钮
        if (submitBtn) {
            submitBtn.disabled = false;
        }
    });
}

// 处理图片提交
function handleImageSubmit(e) {
    e.preventDefault();
    
    const imageFile = document.getElementById('imageFile').files[0];
    if (!imageFile) {
        alert('请选择图片文件');
        return;
    }
    
    // 防止重复提交
    const submitBtn = e.target.querySelector('button[type="submit"]');
    if (submitBtn && submitBtn.disabled) {
        return;
    }
    
    // 禁用提交按钮
    if (submitBtn) {
        submitBtn.disabled = true;
    }
    
    showUploadLoading();
    
    const formData = new FormData();
    formData.append('type', 'image');
    formData.append('file', imageFile);
    
    fetch('/api/content', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        displayUploadResult(data);
        document.getElementById('imageFile').value = '';
        document.getElementById('imagePreview').classList.add('d-none');
        // 重新启用提交按钮
        if (submitBtn) {
            submitBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        displayUploadError(error);
        // 出错时重新启用按钮
        if (submitBtn) {
            submitBtn.disabled = false;
        }
    });
}

// 处理URL提交
function handleUrlSubmit(e) {
    e.preventDefault();
    
    const url = document.getElementById('urlInput').value.trim();
    if (!url) {
        alert('请输入网页链接');
        return;
    }
    
    // 防止重复提交
    const submitBtn = e.target.querySelector('button[type="submit"]');
    if (submitBtn && submitBtn.disabled) {
        return;
    }
    
    // 禁用提交按钮
    if (submitBtn) {
        submitBtn.disabled = true;
    }
    
    showUploadLoading();
    
    const formData = new FormData();
    formData.append('type', 'url');
    formData.append('url', url);
    
    fetch('/api/content', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        displayUploadResult(data);
        document.getElementById('urlInput').value = '';
        // 重新启用提交按钮
        if (submitBtn) {
            submitBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        displayUploadError(error);
        // 出错时重新启用按钮
        if (submitBtn) {
            submitBtn.disabled = false;
        }
    });
}

// 处理文件提交
function handleFileSubmit(e) {
    e.preventDefault();
    
    const fileInput = document.getElementById('uploadFile');
    const file = fileInput.files[0];
    
    if (!file) {
        alert('请选择一个文件');
        return;
    }
    
    // 防止重复提交
    const submitBtn = e.target.querySelector('button[type="submit"]');
    if (submitBtn && submitBtn.disabled) {
        return;
    }
    
    // 禁用提交按钮
    if (submitBtn) {
        submitBtn.disabled = true;
    }
    
    showUploadLoading();
    
    const formData = new FormData();
    formData.append('type', 'file');
    formData.append('file', file);
    
    fetch('/api/content', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        displayUploadResult(data);
        document.getElementById('uploadFile').value = '';
        document.getElementById('filePreview').classList.add('d-none');
        // 重新启用提交按钮
        if (submitBtn) {
            submitBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        displayUploadError(error);
        // 出错时重新启用按钮
        if (submitBtn) {
            submitBtn.disabled = false;
        }
    });
}

// 文件选择预览
function handleFilePreview(e) {
    const file = e.target.files[0];
    const preview = document.getElementById('filePreview');
    const previewName = document.getElementById('filePreviewName');
    const previewSize = document.getElementById('filePreviewSize');

    if (!file) {
        preview.classList.add('d-none');
        const contentBox0 = document.getElementById('filePreviewContent');
        if (contentBox0) contentBox0.innerHTML = '';
        return;
    }

    // 基本信息
    previewName.textContent = file.name;
    previewSize.textContent = `(${(file.size / 1024).toFixed(1)} KB)`;
    preview.classList.remove('d-none');

    // 预览内容容器（不存在则创建）
    let contentBox = document.getElementById('filePreviewContent');
    if (!contentBox) {
        contentBox = document.createElement('div');
        contentBox.id = 'filePreviewContent';
        contentBox.className = 'mt-2';
        preview.appendChild(contentBox);
    } else {
        contentBox.innerHTML = '';
    }

    const nameLower = file.name.toLowerCase();
    const isImage = /\.(jpg|jpeg|png|gif|bmp|webp)$/.test(nameLower);
    const isText = /\.(txt|md|markdown)$/.test(nameLower);
    const isPdf = /\.pdf$/.test(nameLower);

    if (isImage) {
        const reader = new FileReader();
        reader.onload = function(evt) {
            const img = document.createElement('img');
            img.src = evt.target.result;
            img.className = 'img-fluid rounded';
            img.style.maxHeight = '300px';
            img.style.objectFit = 'contain';
            contentBox.appendChild(img);
        };
        reader.readAsDataURL(file);
    } else if (isText) {
        const reader = new FileReader();
        reader.onload = function(evt) {
            const raw = String(evt.target.result || '');
            const snippet = raw.substring(0, 200);
            // 简单转义，防止插入未闭合/恶意标签影响布局
            const escaped = escapeHtml(snippet);
            const pre = document.createElement('pre');
            pre.className = 'p-3 bg-light rounded';
            pre.style.whiteSpace = 'pre-wrap';
            pre.style.wordBreak = 'break-word';
            pre.innerHTML = escaped + (raw.length > 200 ? '\n...\n(预览截断)' : '');
            contentBox.appendChild(pre);
        };
        try {
            reader.readAsText(file, 'utf-8');
        } catch (err) {
            reader.readAsText(file);
        }
    } else if (isPdf) {
        // PDF文件预览
        const pdfInfo = document.createElement('div');
        pdfInfo.className = 'pdf-info p-3 bg-light rounded';
        
        const icon = document.createElement('i');
        icon.className = 'bi bi-file-earmark-pdf text-danger me-2';
        icon.style.fontSize = '2rem';
        
        const infoText = document.createElement('div');
        infoText.innerHTML = `
            <strong>PDF文档</strong>
            <p class="mb-0 text-muted">上传后可在线预览</p>
        `;
        
        pdfInfo.appendChild(icon);
        pdfInfo.appendChild(infoText);
        pdfInfo.style.display = 'flex';
        pdfInfo.style.alignItems = 'center';
        
        contentBox.appendChild(pdfInfo);
    } else {
        contentBox.textContent = '该文件类型不支持内容预览';
        contentBox.classList.add('text-muted');
    }
}

// 图片预览
function handleImagePreview(e) {
    const file = e.target.files[0];
    if (!file) {
        document.getElementById('imagePreview').classList.add('d-none');
        return;
    }
    
    const reader = new FileReader();
    reader.onload = function(event) {
        const img = document.getElementById('imagePreview');
        img.src = event.target.result;
        img.classList.remove('d-none');
    };
    reader.readAsDataURL(file);
}

function genScreenshotName(mime) {
    const d = new Date();
    const pad = n => String(n).padStart(2, '0');
    const ts = `${d.getFullYear()}${pad(d.getMonth()+1)}${pad(d.getDate())}_${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
    const ext = (mime && /jpe?g/i.test(mime)) ? '.jpg' : '.png';
    return `screenshot_${ts}${ext}`;
}

// 显示上传结果
function displayUploadResult(data) {
    const container = document.getElementById('uploadResult');
    const resultContainer = document.getElementById('uploadResultContainer');
    
    if (data.error) {
        container.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-exclamation-triangle me-2"></i>
                ${data.error}
            </div>
        `;
        resultContainer.classList.remove('d-none');
        return;
    }
    
    let keywordsHtml = '';
    if (data.keywords && data.keywords.length > 0) {
        keywordsHtml = data.keywords.map(keyword => 
            `<span class="badge bg-primary keyword-badge" onclick="searchFromUpload('${keyword}')">${keyword}</span>`
        ).join(' ');
    }
    
    container.innerHTML = `
        <div class="alert alert-success">
            <h5><i class="bi bi-check-circle me-2"></i>处理完成</h5>
            <p><strong>内容ID:</strong> <code>${data.id}</code></p>
            <div class="mt-3">
                <strong>提取的关键词:</strong>
                <div class="mt-2">${keywordsHtml || '<span class="text-muted">无关键词</span>'}</div>
            </div>
            <div class="mt-3">
                <strong>内容摘要:</strong>
                <p class="mt-2 p-3 bg-light rounded">${data.summary || '无摘要'}</p>
            </div>
            <div class="mt-3">
                <button class="btn btn-outline-primary me-2" onclick="showSearchPage()">
                    <i class="bi bi-search me-2"></i>去搜索
                </button>
                <button class="btn btn-outline-secondary" onclick="clearUploadResult()">
                    <i class="bi bi-x-circle me-2"></i>清除结果
                </button>
            </div>
        </div>
    `;
    
    resultContainer.classList.remove('d-none');
    resultContainer.scrollIntoView({ behavior: 'smooth' });
}

// 显示上传错误
function displayUploadError(error) {
    const container = document.getElementById('uploadResult');
    const resultContainer = document.getElementById('uploadResultContainer');
    
    container.innerHTML = `
        <div class="alert alert-danger">
            <i class="bi bi-exclamation-triangle me-2"></i>
            处理失败: ${error.message || '未知错误'}
        </div>
    `;
    
    resultContainer.classList.remove('d-none');
}

// 清除上传结果
function clearUploadResult() {
    document.getElementById('uploadResultContainer').classList.add('d-none');
}

// 从上传页面搜索关键词
function searchFromUpload(keyword) {
    document.getElementById('mainSearchInput').value = keyword;
    showSearchPage();
    setTimeout(() => {
        handleMainSearch();
    }, 300);
}

// 显示上传加载状态
function showUploadLoading() {
    const container = document.getElementById('uploadResult');
    const resultContainer = document.getElementById('uploadResultContainer');
    
    container.innerHTML = `
        <div class="text-center p-4">
            <div class="spinner-border text-primary mb-3" role="status">
                <span class="visually-hidden">处理中...</span>
            </div>
            <p class="mb-0">正在处理内容，请稍候...</p>
        </div>
    `;
    
    resultContainer.classList.remove('d-none');
}

// ==== 粘贴截图预览与提交 ====
function previewPastedImage(file) {
    pastedImageFile = file;
    try {
        const imgEl = document.getElementById('imagePreview');
        if (imgEl && file) {
            const fr = new FileReader();
            fr.onload = function(evt) {
                imgEl.src = evt.target.result;
                imgEl.classList.remove('d-none');
            };
            fr.readAsDataURL(file);
        }
    } catch (e) {
        console.warn('preview pasted image failed', e);
    }
    const btn = document.getElementById('uploadPastedImageBtn');
    if (btn) {
        btn.disabled = false;
        btn.classList.remove('d-none');
        btn.onclick = uploadPastedImageSubmit;
    }
}

function uploadPastedImageSubmit() {
    if (!pastedImageFile) {
        alert('没有可上传的截图，请先粘贴图片');
        return;
    }
    
    // 防止重复提交
    const btn = document.getElementById('uploadPastedImageBtn');
    if (btn && btn.disabled) {
        return;
    }
    
    // 禁用按钮，防止重复点击
    if (btn) {
        btn.disabled = true;
    }
    
    showUploadLoading();

    const formData = new FormData();
    formData.append('type', 'image');
    formData.append('file', pastedImageFile, genScreenshotName(pastedImageFile.type));

    fetch('/api/content', { method: 'POST', body: formData })
        .then(response => response.json())
        .then(data => {
            displayUploadResult(data);
            pastedImageFile = null;
            const btn = document.getElementById('uploadPastedImageBtn');
            if (btn) btn.disabled = true;
            const imgEl = document.getElementById('imagePreview');
            if (imgEl) {
                imgEl.classList.add('d-none');
                imgEl.removeAttribute('src');
            }
        })
        .catch(error => {
            console.error('上传截图失败:', error);
            displayUploadError(error);
            // 出错时重新启用按钮
            if (btn) {
                btn.disabled = false;
            }
        });
}

// 粘贴截图上传检测
function isImageUploadVisible() {
    // 1) 上传页可见
    const uploadPage = document.getElementById('uploadPage');
    const uploadVisible = uploadPage && !uploadPage.classList.contains('d-none');

    if (!uploadVisible) return false;

    // 2) 图片Tab是否激活（多重兜底，适配不同模板）
    // 2.1 Tab 内容面板激活（图片面板为 #image-input）
    const imagePaneActive = document.querySelector('.tab-pane#image-input.show.active') !== null;

    // 2.2 Tab 按钮激活（按钮ID为 #image-tab，或 data-bs-target="#image-input"）
    const imageTabBtnActive = document.querySelector('#image-tab.active, #image-tab[aria-selected="true"], [data-bs-target="#image-input"].active, [data-bs-target="#image-input"][aria-selected="true"]') !== null;

    // 2.3 直接检查可能的图片上传容器是否可见
    const imageSection = document.getElementById('imageUploadSection') || document.getElementById('imageTab') || document.getElementById('imageFormSection') || document.getElementById('image-input');
    const imageSectionVisible = imageSection ? !imageSection.classList.contains('d-none') : false;

    return imagePaneActive || imageTabBtnActive || imageSectionVisible;
}

// 粘贴事件处理
const pasteHandler = function(e) {
    if (!isImageUploadVisible()) return;
    if (!e.clipboardData || !e.clipboardData.items) return;
    for (const item of e.clipboardData.items) {
        if (item.type && item.type.indexOf('image') === 0) {
            const file = item.getAsFile();
            if (file) {
                e.preventDefault();
                previewPastedImage(file);
                const btn = document.getElementById('uploadPastedImageBtn');
                if (btn) btn.disabled = false;
                return;
            }
        }
    }
};

// 初始化上传模块
document.addEventListener('DOMContentLoaded', function() {
    // 绑定上传相关事件监听器
    document.getElementById('uploadButton').addEventListener('click', showUploadPage);
    document.getElementById('textForm').addEventListener('submit', handleTextSubmit);
    document.getElementById('fileForm').addEventListener('submit', handleFileSubmit);
    document.getElementById('urlForm').addEventListener('submit', handleUrlSubmit);
    
    // 文件选择预览
    document.getElementById('uploadFile').addEventListener('change', handleFilePreview);
    
    // 粘贴截图上传（切到"图片上传"页时，Ctrl+V / Cmd+V 全局生效）
    // 先移除可能存在的重复事件监听器，再添加新的
    document.removeEventListener('paste', pasteHandler);
    document.addEventListener('paste', pasteHandler);

    // 绑定"上传截图"按钮
    const uploadPastedBtn = document.getElementById('uploadPastedImageBtn');
    if (uploadPastedBtn) {
        uploadPastedBtn.removeEventListener('click', uploadPastedImageSubmit);
        uploadPastedBtn.addEventListener('click', uploadPastedImageSubmit);
        uploadPastedBtn.disabled = !pastedImageFile;
    }
});